<template>
  <AdminLayout title="编辑规格模板" :subtitle="`编辑模板：${template.name}`">
    <div class="max-w-4xl">
      <form @submit.prevent="submit" class="space-y-6">
        <div class="bg-white shadow-sm rounded-lg">
          <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-medium text-gray-900">模板基本信息</h3>
          </div>
          
          <div class="px-6 py-4 space-y-6">
            <!-- 模板名称 -->
            <div>
              <label for="name" class="block text-sm font-medium text-gray-700">
                模板名称 <span class="text-red-500">*</span>
              </label>
              <input 
                id="name"
                v-model="form.name"
                type="text" 
                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                :class="{ 'border-red-300': errors.name }"
                placeholder="请输入模板名称，如：Orange Phone 颜色规格"
              />
              <p v-if="errors.name" class="mt-1 text-sm text-red-600">{{ errors.name }}</p>
            </div>

            <!-- 模板别名 -->
            <div>
              <label for="slug" class="block text-sm font-medium text-gray-700">
                模板别名 <span class="text-red-500">*</span>
              </label>
              <input 
                id="slug"
                v-model="form.slug"
                type="text" 
                readonly
                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm bg-gray-50 text-gray-500 sm:text-sm"
                placeholder="模板别名不可修改"
              />
              <p class="mt-1 text-sm text-gray-500">模板别名不可修改，用于系统内部标识</p>
            </div>

            <!-- 模板描述 -->
            <div>
              <label for="description" class="block text-sm font-medium text-gray-700">
                模板描述
              </label>
              <textarea 
                id="description"
                v-model="form.description"
                rows="3"
                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                :class="{ 'border-red-300': errors.description }"
                placeholder="请输入模板描述"
              ></textarea>
              <p v-if="errors.description" class="mt-1 text-sm text-red-600">{{ errors.description }}</p>
            </div>

            <!-- 适用分类 -->
            <div>
              <label for="category_id" class="block text-sm font-medium text-gray-700">
                适用分类
              </label>
              <select 
                id="category_id"
                v-model="form.category_id"
                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                :class="{ 'border-red-300': errors.category_id }"
              >
                <option value="">选择分类（留空表示全局模板）</option>
                <option v-for="category in categories" :key="category.id" :value="category.id">
                  {{ category.name }}
                </option>
              </select>
              <p v-if="errors.category_id" class="mt-1 text-sm text-red-600">{{ errors.category_id }}</p>
              <p class="mt-1 text-sm text-gray-500">选择特定分类或留空创建全局模板</p>
            </div>

            <!-- 排序顺序 -->
            <div>
              <label for="sort_order" class="block text-sm font-medium text-gray-700">
                排序顺序
              </label>
              <input 
                id="sort_order"
                v-model.number="form.sort_order"
                type="number" 
                min="0"
                class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                :class="{ 'border-red-300': errors.sort_order }"
                placeholder="0"
              />
              <p v-if="errors.sort_order" class="mt-1 text-sm text-red-600">{{ errors.sort_order }}</p>
              <p class="mt-1 text-sm text-gray-500">数字越大排序越靠前</p>
            </div>

            <!-- 模板配置 -->
            <div class="space-y-4">
              <h4 class="text-sm font-medium text-gray-900">模板配置</h4>
              
              <div class="flex items-center">
                <input 
                  id="is_active"
                  v-model="form.is_active"
                  type="checkbox" 
                  class="h-4 w-4 text-gray-900 focus:ring-gray-900 border-gray-300 rounded"
                />
                <label for="is_active" class="ml-2 block text-sm text-gray-900">
                  启用此模板
                </label>
              </div>

              <div class="flex items-center">
                <input 
                  id="is_default"
                  v-model="form.is_default"
                  type="checkbox" 
                  class="h-4 w-4 text-gray-900 focus:ring-gray-900 border-gray-300 rounded"
                />
                <label for="is_default" class="ml-2 block text-sm text-gray-900">
                  设为默认模板
                </label>
              </div>
            </div>
          </div>
        </div>

        <!-- 规格属性配置 -->
        <div class="bg-white shadow-sm rounded-lg">
          <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-medium text-gray-900">规格属性配置</h3>
            <p class="mt-1 text-sm text-gray-500">配置此模板包含的规格属性</p>
          </div>
          
          <div class="px-6 py-4">
            <div class="space-y-4">
              <div v-for="(attribute, index) in form.attributes_config" :key="index" 
                   class="border border-gray-200 rounded-lg p-4">
                <div class="flex items-center justify-between mb-4">
                  <h5 class="text-sm font-medium text-gray-900">
                    规格属性 {{ index + 1 }}
                  </h5>
                  <button 
                    type="button"
                    @click="removeAttribute(index)"
                    class="text-red-600 hover:text-red-900 transition-colors duration-200"
                  >
                    <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                    </svg>
                  </button>
                </div>
                
                <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
                  <div>
                    <label class="block text-xs font-medium text-gray-700">属性名称</label>
                    <input 
                      v-model="attribute.name"
                      type="text" 
                      class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 text-sm"
                      placeholder="如：颜色"
                    />
                  </div>
                  <div>
                    <label class="block text-xs font-medium text-gray-700">属性别名</label>
                    <input 
                      v-model="attribute.slug"
                      type="text" 
                      class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 text-sm"
                      placeholder="如：color"
                    />
                  </div>
                  <div>
                    <label class="block text-xs font-medium text-gray-700">属性类型</label>
                    <select 
                      v-model="attribute.type"
                      class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 text-sm"
                    >
                      <option value="select">下拉选择</option>
                      <option value="color">颜色选择</option>
                      <option value="size">尺寸选择</option>
                      <option value="text">文本输入</option>
                      <option value="number">数字输入</option>
                    </select>
                  </div>
                  <div class="flex items-center space-x-4">
                    <div class="flex items-center">
                      <input 
                        v-model="attribute.is_required"
                        type="checkbox" 
                        class="h-4 w-4 text-gray-900 focus:ring-gray-900 border-gray-300 rounded"
                      />
                      <label class="ml-2 block text-xs text-gray-900">必选</label>
                    </div>
                    <div class="flex items-center">
                      <input 
                        v-model="attribute.is_variant"
                        type="checkbox" 
                        class="h-4 w-4 text-gray-900 focus:ring-gray-900 border-gray-300 rounded"
                      />
                      <label class="ml-2 block text-xs text-gray-900">影响规格型号</label>
                    </div>
                  </div>
                </div>
                
                <!-- 属性选项 -->
                <div v-if="attribute.type === 'select' || attribute.type === 'color' || attribute.type === 'size'" class="mt-4">
                  <label class="block text-xs font-medium text-gray-700">属性选项</label>
                  <div class="mt-2 space-y-2">
                    <div v-for="(option, optionIndex) in attribute.options" :key="optionIndex" 
                         class="flex items-center space-x-2">
                      <input 
                        v-model="attribute.options[optionIndex].name"
                        type="text" 
                        class="flex-1 border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 text-sm"
                        :placeholder="`选项名称 ${optionIndex + 1}`"
                      />
                      <input 
                        v-model="attribute.options[optionIndex].value"
                        type="text" 
                        class="flex-1 border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 text-sm"
                        :placeholder="`选项值 ${optionIndex + 1}`"
                      />
                      <button 
                        type="button"
                        @click="removeOption(index, optionIndex)"
                        class="text-red-600 hover:text-red-900 transition-colors duration-200"
                      >
                        <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                        </svg>
                      </button>
                    </div>
                    <button 
                      type="button"
                      @click="addOption(index)"
                      class="inline-flex items-center px-3 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-colors duration-200"
                    >
                      <svg class="-ml-1 mr-2 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                      </svg>
                      添加选项
                    </button>
                  </div>
                </div>
              </div>
              
              <button 
                type="button"
                @click="addAttribute"
                class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-colors duration-200"
              >
                <svg class="-ml-1 mr-2 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                </svg>
                添加规格属性
              </button>
            </div>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="flex justify-end space-x-3">
          <Link :href="route('admin.specification-templates.index')" 
                class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-colors duration-200">
            取消
          </Link>
          <button 
            type="submit" 
            :disabled="processing"
            class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-gray-900 hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200"
          >
            <svg v-if="processing" class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
              <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            {{ processing ? '更新中...' : '更新规格模板' }}
          </button>
        </div>
      </form>
    </div>
  </AdminLayout>
</template>

<script setup>
import { ref } from 'vue'
import { Link, useForm } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'

const props = defineProps({
  template: {
    type: Object,
    required: true
  },
  categories: {
    type: Array,
    required: true
  }
})

const form = useForm({
  name: props.template.name,
  slug: props.template.slug,
  description: props.template.description || '',
  category_id: props.template.category_id,
  attributes_config: props.template.attributes_config || [],
  display_config: props.template.display_config || {},
  is_active: props.template.is_active,
  is_default: props.template.is_default,
  sort_order: props.template.sort_order,
})

const processing = ref(false)

const addAttribute = () => {
  form.attributes_config.push({
    name: '',
    slug: '',
    type: 'select',
    options: [{ name: '', value: '' }],
    is_required: true,
    is_variant: true,
  })
}

const removeAttribute = (index) => {
  if (form.attributes_config.length > 0) {
    form.attributes_config.splice(index, 1)
  }
}

const addOption = (attributeIndex) => {
  form.attributes_config[attributeIndex].options.push({ name: '', value: '' })
}

const removeOption = (attributeIndex, optionIndex) => {
  if (form.attributes_config[attributeIndex].options.length > 1) {
    form.attributes_config[attributeIndex].options.splice(optionIndex, 1)
  }
}

const submit = () => {
  // 过滤空选项
  form.attributes_config = form.attributes_config.map(attribute => ({
    ...attribute,
    options: attribute.options.filter(option => 
      (typeof option === 'string' && option.trim() !== '') ||
      (typeof option === 'object' && option.name && option.name.trim() !== '')
    )
  }))
  
  processing.value = true
  form.put(route('admin.specification-templates.update', props.template.id), {
    onFinish: () => {
      processing.value = false
    }
  })
}

const errors = form.errors
</script>
